/**  定义地址薄 相关的接口 */
const express = require("express");
const router = express.Router();
const Response = require("../utils/Response.js");

// 引入mysql连接池
const pool = require("../utils/db.js");

/**
 * 根据用户id查询地址
 */
router.get("/address_book/select", (req, resp) => {
  let { user_id } = req.query
  let sql = "select * from address_book where user_id = ?";
  pool.query(sql, [user_id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result.length===0) {
      resp.send(Response.error(404, '该用户暂无添加地址薄'));
    } else {
     let address =result.map(item=>{
      return{
        id:item.address_id,
        name:item.name,
        tel:item.phone,
        address:item.province+item.city+item.county+item.address
      }
     })
      resp.send(Response.ok(address));
    }

  });
})

/**
 *根据当前用户id添加地址
 */
router.post("/address_book/add", (req, resp) => {
  let sql = "insert into address_book set ?"
  pool.query(sql, [req.body], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result.affectedRows === 0) {
      resp.send(Response.error(501, '新增失败'));
    } else {
      resp.send(Response.ok('新增成功'))
    }
  })
})

/**
 *根据当前用户id删除地址
 */
router.post("/address_book/delete", (req, resp) => {
  let { user_id, address_id } = req.body
  let sql = "delete from address_book where user_id =? and address_id = ?"
  pool.query(sql, [user_id, address_id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }

    if (result.affectedRows === 0) {
      resp.send(Response.error(502, '删除失败'));
    } else {
      resp.send(Response.ok('删除成功'))
    }

  })
})

/**
 *根据当前用户id修改地址
 */
router.post("/address_book/update", (req, resp) => {
  let { user_id, address_id } = req.body
  let sql = "update address_book set ? where user_id =? and address_id = ?"
  pool.query(sql, [req.body, user_id, address_id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result.changedRows === 0) {
      resp.send(Response.error(503, '修改失败'));
    } else {
      resp.send(Response.ok('修改成功'))
    }

  })
})

//通过id查询地址
router.get("/address_book/query", (req, resp) => {
  let { address_id } = req.query
  let sql = "select *  from address_book where address_id = ?";
  pool.query(sql, [address_id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result.length===0) {
      resp.send(Response.error(500, '该用户暂无添加地址薄'));
    } else {
      resp.send(Response.ok(result));
    }
  });
})



// 将router对象导出
module.exports = router;
